package com.lagou.demo.service.impl;

import com.lagou.demo.service.HandlerInteceptor;
import com.lagou.edu.mvcframework.annotations.LagouSecurity;
import com.lagou.edu.mvcframework.annotations.LagouService;
import com.lagou.edu.mvcframework.pojo.Handler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 拦截器处理的前置方法的具体实现类
 */
@LagouService(value = "handlerInteceptorImpl")
public class HandlerInteceptorImpl implements HandlerInteceptor {
    @Override
    public void preHandle(HttpServletRequest HttpServletRequest, HttpServletResponse httpServletResponse, Handler handler) {
        //1、获取类上注解
        LagouSecurity lagouSecurityClass = handler.getController().getClass().getAnnotation(LagouSecurity.class);

        //2、获取方法上面的注解值
        LagouSecurity lagouSecurityMethod = handler.getMethod().getAnnotation(LagouSecurity.class);

        //3、获取传入参数值
        String name = HttpServletRequest.getParameter("name");

        //4、获取注解值
        if (lagouSecurityClass==null && lagouSecurityMethod == null) {
            return;
        }

        if (name == null) {
            throw new RuntimeException("name is null not permission");
        }

        //5、判断是否符合相关权限
        String [] securityclass = {};
        String [] securityMethod = {};
        if (lagouSecurityClass!=null) {
            securityclass =  lagouSecurityClass.value();
        }
        if (securityMethod!=null) {
            securityMethod = lagouSecurityMethod.value();
        }

        boolean permission = true;  //默认允许验证通过

        for (String classname: securityclass
             ) {
            permission = false;
            if (name.equals(classname)) {
                return;
            }
        }
        if (!permission) {
            throw new RuntimeException(name + "is not permission");
        }

        for (String classmethod: securityMethod
        ) {
            if (name.equals(classmethod)) {
                return;
            }
        }

        throw new RuntimeException(name + "is not permission");


    }
}
